<?php

namespace App\Http\Controllers\Article;

use App\Model\article;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleController extends Controller
{
    public function __construct()
    {
        $this->middleware('check.login');
    }

    protected static $fileName;//生成的图片名
    protected static $headTimePath;//生成的头部加时间的图片路径
    protected static $textPath;//生成的文字图片路径
    protected static $textImagePath;//生成文字头部底部的图片路径

    //生产组合后的图片
    public function createImage($articles){
        //转换文字排列样式
        $content = "";
        $num=0;
        //以下换成您自己的字体
        $fontface= './font/rhGBK.ttf';
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        for ($i=0;$i<mb_strlen($articles,'utf-8');$i++) {
            $letter[] = mb_substr($articles, $i, 1,'utf-8');
        }
        $teststr ='';
        foreach ($letter as $l) {
            $teststr .= $l;
            $testbox = imagettfbbox(30, 0, $fontface, $teststr);
            // 判断拼接后的字符串是否超过预设的宽度
            if (($testbox[2] > 650) && ($content !== "")) {
                $content .= "\n";
                $num++;
                $teststr=$l;
            }
            $content .= $l;
        }

        //生成文字图片
        try {

            $font = "./font/hwxh.ttf";
            $texts = $content;

            //获得当前的时间
            $time = date("Y-m-d H:i:s");
            $weeks= mb_substr( "日一二三四五六",date("w"),1,"utf-8" );
            $text1 = "今天·".$time."·星期".$weeks."";

            //组合上传图片路径
            $headTimePaths = "./uploadImg/headTime/".date('ymd');
            $textPaths = "./uploadImg/text/".date('ymd');
            $textImagePaths = "./uploadImg/textImage/".date('ymd');
            if (file_exists($headTimePaths)){
                self::$headTimePath = $headTimePaths;
            }else{
                mkdir('./uploadImg/headTime/'.date('ymd'));
                self::$headTimePath = $headTimePaths;
            }

            if (file_exists($textPaths)){
                self::$textPath = $textPaths;
            }else{
                mkdir('./uploadImg/text/'.date('ymd'));
                self::$textPath = $textPaths;
            }

            if (file_exists($textImagePaths)){
                self::$textImagePath = $textImagePaths;
            }else{
                mkdir('./uploadImg/textImage/'.date('ymd'));
                self::$textImagePath = $textImagePaths;
            }
            self::$fileName =date('ymd').time().mt_rand(0,100);

            $options = [
                'fontFile' => $font,
                'size' => 60,
                'color' => 'black',
                'anchor' => 'top',
                'xOffset' => 0,
                'yOffset' => 0,
                'shadow' => null
            ];
            $options1 = [
                'fontFile' => $font,
                'size' => 40,
                'color' => '#888',
                'anchor' => 'left',
                'xOffset' => 140,
                'yOffset' => 0,
                'shadow' => null
            ];

            //生成时间图片
            $time = new \claviska\SimpleImage();
            $time ->fromNew(1125,200,"white")
                  ->overlay('./images/time.png', "left",1,60,0)  // 添加水印图像
                  ->text($text1,$options1 )
                  ->toFile('./uploadImg/time.png', 'image/png');

            //生成头部和时间的组合图片
            $head = new \claviska\SimpleImage();
            $head ->fromNew(1125,875,"white")
                ->overlay('./images/head.png', "top",1)  // 添加水印图像
                ->overlay('./uploadImg/time.png', "bottom",1)  // 添加水印图像
                ->toFile(self::$headTimePath.'/'.self::$fileName.'.png', 'image/png');

            //生成低部图片
            $head = new \claviska\SimpleImage();
            $head ->fromNew(1125,385,"white")
                ->overlay('./images/bottom.png', "top",1)  // 添加水印图像
                ->toFile('./uploadImg/bottom.png', 'image/png');

            //生成新闻内容图片
            $text = new \claviska\SimpleImage();
            $text ->fromNew(1125,$num*(30+73),"white")
                ->text($texts,$options )
                ->toFile(self::$textPath.'/'.self::$fileName.'.png', 'image/png');


            //生成文字和背景图组合图
            $image = new \claviska\SimpleImage();
            $image
                ->fromNew(1125,$num*(30+73)+875+385,"white")
                ->overlay(self::$headTimePath.'/'.self::$fileName.'.png', "top",1,0,0)  // 添加水印图像
                ->overlay(self::$textPath.'/'.self::$fileName.'.png', "center",1,0,200)  // 添加水印图像
                ->overlay('./uploadImg/bottom.png', "bottom",1)  // 添加水印图像
                ->toFile(self::$textImagePath.'/'.self::$fileName.'.png', 'image/png') ;   // 转换为PNG并保存一份副本到新image.png
        } catch(Exception $err) {
            // Handle errors
            echo $err->getMessage();
        }
    }

    /**加载文章列表页
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $article =  article::paginate(10);
        return view("article.index",compact("article"));
    }

    /**展示添加页面
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view("article.create");
    }

    /**添加文章
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->all();
        //获得转换的图片
//        dd($data);/
        $this->createImage($data['content']);
        isset($data['important']) ? $data['important'] : $data['important'] = 0 ;
        $data =[
            "content"=>$data['content'],
            "thumb"=>'http://'.$_SERVER['SERVER_NAME'].ltrim(self::$textImagePath,'.').'/'.self::$fileName.'.png',
            "important"=>$data['important']
        ];
        article::create($data);
        flash()->overlay('添加成功', '消息提醒');
        return redirect("/article/index");
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *展示编辑页面
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //获得当前文章数据
        $model = article::find($id);
        return view("article.edit",compact("model"));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->all();
        //获得当前文章数据
        isset($data['important']) ? $data['important'] : $data['important'] = 0 ;
        $model = article::find($id);
        $model -> content = $data['content'];
        $model -> important = $data['important'];
        //获得转换的图片
        $this->createImage($data['content']);
        $model -> thumb = 'http://'.$_SERVER['SERVER_NAME'].ltrim(self::$textImagePath,'.').'/'.self::$fileName.'.png';
        $model ->save();
        flash()->overlay('修改成功', '消息提醒');
        return redirect("article/index");
    }

    /**删除当前文章
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        article::destroy($id);
         return response()->json(['valid'=>1,'message'=>'删除成功']);
    }
}
